//
//  SWImageUtil.m
//  YiyaPuzzleDemo
//
//  Created by linhan on 16/10/26.
//  Copyright © 2016年 test. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <ImageIO/ImageIO.h>
#import <UIKit/UIKit.h>
#import "SWImageUtil.h"

@implementation SWImageUtil

+ (NSData *)changeImageResolution:(NSData *)sourceImageData resolution:(NSInteger)resolution
{
    CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)sourceImageData, NULL);
    
    NSDictionary *metadata = (__bridge_transfer NSDictionary *)CGImageSourceCopyPropertiesAtIndex(source, 0, NULL);
    
    NSMutableDictionary *tempMetadata = [metadata mutableCopy];
    [tempMetadata setObject:[NSNumber numberWithInteger:resolution] forKey:@"DPIHeight"];
    [tempMetadata setObject:[NSNumber numberWithInteger:resolution] forKey:@"DPIWidth"];
    
    NSMutableDictionary *EXIFDictionary = [[tempMetadata objectForKey:(NSString *)kCGImagePropertyTIFFDictionary] mutableCopy];
    //密度单位 0:不使用单位 1:dot 2:英寸 3:厘米
    [EXIFDictionary setObject:@(2) forKey:(NSString *)kCGImagePropertyTIFFResolutionUnit];
    [EXIFDictionary setObject:[NSNumber numberWithInteger:resolution] forKey:(NSString *)kCGImagePropertyTIFFXResolution];
    [EXIFDictionary setObject:[NSNumber numberWithInteger:resolution] forKey:(NSString *)kCGImagePropertyTIFFYResolution];
    
    NSMutableDictionary *JFIFDictionary = [[NSMutableDictionary alloc] init];
    [JFIFDictionary setObject:[NSNumber numberWithInteger:resolution] forKey:(NSString *)kCGImagePropertyJFIFXDensity];
    [JFIFDictionary setObject:[NSNumber numberWithInteger:resolution] forKey:(NSString *)kCGImagePropertyJFIFYDensity];
    [JFIFDictionary setObject:@"1" forKey:(NSString *)kCGImagePropertyJFIFVersion];
    
    [tempMetadata setObject:EXIFDictionary forKey:(NSString *)kCGImagePropertyTIFFDictionary];
    [tempMetadata setObject:JFIFDictionary forKey:(NSString *)kCGImagePropertyJFIFDictionary];
    
    NSMutableData *destinationImageData = [NSMutableData data];
    
    CFStringRef UTI = CGImageSourceGetType(source);
    
    CGImageDestinationRef destination = CGImageDestinationCreateWithData((__bridge CFMutableDataRef)destinationImageData, UTI, 1, NULL);
    
    CGImageDestinationAddImageFromSource(destination, source,0, (__bridge CFDictionaryRef) tempMetadata);
    
    CGImageDestinationFinalize(destination);
    
    return destinationImageData;
}

+ (CIContext*) ContextMake
{
    return [CIContext contextWithOptions:nil];
}

@end
